package ace.cmp.spring.util.core;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import java.util.Set;

/**
 * @author caspar
 * @date 2023/10/24 10:46
 */
public class ValidatorUtils {
  private final Validator validator;

  public ValidatorUtils(Validator validator) {
    this.validator = validator;
  }

  public <T> Set<ConstraintViolation<T>> validate(T object) {
    return this.validator.validate(object);
  }

  public <T> void validateThrowFirst(T object) {
    Set<? extends ConstraintViolation<?>> constraintViolations = this.validate(object);
    if (constraintViolations != null && !constraintViolations.isEmpty()) {
      throw new ConstraintViolationException(constraintViolations);
    }
  }
}
